﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using QuanLyThuPhiTaiLieu.Common;
using QuanLyThuPhiTaiLieu.Entity;
using QuanLyThuPhiTaiLieu.Model;

namespace QuanLyThuPhiTaiLieu.Biz.QuanTriHeThong
{
    public class GuestBiz : BaseBiz
    {
        public int SaveItem(Guest item)
        {
            var dbContext = new Context();
            dbContext.Guests.Add(item);
            int newId = dbContext.SaveChanges();

            return newId;
        }

        public void UpdateItem(Guest item)
        {
            var dbContext = new Context();
            dbContext.Entry(item).State = EntityState.Modified;
            dbContext.SaveChanges();
        }

        public List<Guest> ViewAll()
        {
            var dbContext = new Context();
            return (from item in dbContext.Guests
                    orderby item.Account ascending
                    select item).ToList();
        }

        public Guest LoadItem(int id)
        {
            var dbContext = new Context();
            return (from item in dbContext.Guests
                    where item.Id == id
                    select item).First();
        }

        public string ResetPassword(int id)
        {
            var dbContext = new Context();
            var item = LoadItem(id);
            item.Password = Utilities.EncodePassword(Constants.DefaultPassword);
            UpdateItem(item);

            return item.Password;
        }

        public Guest Login(string account, string password)
        {
            var encodedPassword = Utilities.EncodePassword(password);

            var dbContext = new Context();
            var users = (from item in dbContext.Guests
                         where (item.Account == account && item.Password == encodedPassword)
                         select item);

            if (!users.Any())
            {
                return null;
            }
            return users.First();
        }

        public void RemoveItem(List<Guest> items)
        {
            using (var dbContext = new Context())
            {
                foreach (var tailieu in items)
                {
                    dbContext.Guests.Attach(tailieu);
                    dbContext.Guests.Remove(tailieu);
                    dbContext.Entry(tailieu).State = EntityState.Deleted;
                }

                dbContext.SaveChanges();
            }
        }

        public void UpdateRoles(int userId, string roles)
        {
            var user = new Guest() { Id = userId, Roles = roles };
            using (var dbContext = new Context())
            {
                dbContext.Guests.Attach(user);
                dbContext.Entry(user).Property(x => x.Roles).IsModified = true;
                dbContext.SaveChanges();
            }
        }
    }
}
